package com.paic.mhis.hcpms.agreement.protocol.web.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.paic.mhis.common.util.HttpProcessUtil;
import com.paic.mhis.common.validator.FileValidator;
import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.agreement.protocol.biz.service.AgreementService;
import com.paic.mhis.hcpms.agreement.protocol.dto.FileInfoDTO;
import com.paic.mhis.hcpms.common.uploadFile.biz.service.UploadFileService;
import com.paic.pafa.app.lwc.core.util.DevLog;
import com.paic.pafa.app.lwc.core.util.FileCopyUtils;
import com.paic.pafa.appclient.annotation.BizServicesProxy;
import com.paic.pafa.web.BaseRest;

/**
 * Description: 协议信息模块
 * 
 * @param args
 * 
 *            Modification History: Date Version Author Description
 *            ------------------------------------------------------------------
 *            2214-5-4 hcpms_j2ee EX-LUORONG221 创建
 */
@Controller
@RequestMapping("/agreement/")
public class AgreementController extends BaseRest {
	/**
	 * 协议信息注入
	 */
	private static final Logger logger = Logger
			.getLogger(AgreementController.class);

	@Value("${hcpmsDownloadPath}")
	private String filePath;

	@BizServicesProxy
	private AgreementService agreementService;

	// @Autowired
	// private MessagePublish redisQueuePublish;
	// @Autowired
	// private RedisService redisService;
	@BizServicesProxy
	private UploadFileService uploadFileService;

	// @Autowired
	// private ControllerUtil controllerUtil;

	public AgreementService getAgreementService() {
		return agreementService;
	}

	public void setAgreementService(AgreementService agreementService) {
		this.agreementService = agreementService;
	}

	/**
	 * 协议信息新增
	 */
	@RequestMapping(value = "agreementCreate.do")
	public Map<String, Object> add(HttpServletRequest request) throws Exception {
		Map<String, Object> result = null;
		try {
			UserDetails user = (UserDetails) request.getSession().getAttribute(
					"user");
			String str = HttpProcessUtil.readRequestBody(request);
			JSONObject transferJson = JSON.parseObject(str);
			transferJson.put("createdBy", user.getUsername());
			transferJson.put("updatedBy", user.getUsername());
			// assembleTransferJson(request, transferJson);

			result = this.agreementService
					.add(transferJson, user.getUsername());
			result.put("path", filePath);

		} catch (Exception e) {
			result = HttpProcessUtil.processException(e);
		}
		return result;
	}

	/**
	 * 文件信息新增
	 */
	@RequestMapping(value = "imageInfoCreate.do")
	public Map<String, Object> addImage(HttpServletRequest request)
			throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		FileInfoDTO infoDTO = null;
		try {
			UserDetails user = (UserDetails) request.getSession().getAttribute(
					"user");
			MultipartResolver resolver = new CommonsMultipartResolver(request
					.getSession().getServletContext());
			MultipartHttpServletRequest multiRequest = resolver
					.resolveMultipart(request);
			List<MultipartFile> files = multiRequest.getFiles("file");
			if (!FileValidator.validateFile(files, result)) {
				result.put("result", "0");
				return result;
			}

			JSONObject transferJson = new JSONObject();
			transferJson.put("createdBy", user.getUsername());
			transferJson.put("updatedBy", user.getUsername());
			transferJson.put("id", request.getParameter("id"));
			// assembleTransferJson(request, transferJson);
			infoDTO = JSONObject.toJavaObject(transferJson, FileInfoDTO.class);
			// 文件路径
			String path = File.separator + infoDTO.getId() + File.separator
					+ "insurance";
			for (int i = 0; i < files.size(); i++) {
				String fileName = files.get(i).getOriginalFilename();
				long fileSizeTemp = files.get(i).getSize();
				final byte[] fileContent = files.get(i).getBytes();
				// // 发布消息
				uploadFileService.publishMsg(fileContent, fileName, path);
				result = this.agreementService.addImage(transferJson,
						user.getUsername(), fileName, fileSizeTemp);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = HttpProcessUtil.processException(e);
		}
		return result;
	}

	/**
	 * // 上传文件
	 * 
	 * @param fileName
	 * @param index
	 * @param fileContent
	 * @throws IOException
	 */
	private void uploadFile(String fileName, String index, byte[] fileContent,
			String path) throws IOException {

		try {
			// 文件上传路径
			String fPath = filePath + File.separator + path;
			logger.info("--------------" + fileName + "----" + fPath
					+ "-----------------------------");
			// 如果目录不存在，创建它
			File dirPath = new File(fPath);
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}
			final File uploadFile = new File(fPath, fileName);
			byte[] k = fileContent;
			FileCopyUtils.copy(k, uploadFile);
		} catch (Exception e) {
			logger.error(e);
		}

	}

	@RequestMapping(value = "exitFile.do")
	public Map<String, Object> openPdfFile(HttpServletRequest request)
			throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String str = HttpProcessUtil.readRequestBody(request);
			JSONObject transferJson = JSON.parseObject(str);
			String filepath = transferJson.getString("filePath");
			File file = new File(filepath);
			boolean bFile = file.exists();
			// 判断文件路径是否存在
			if (!bFile) {
				result.put("state", "error");
				result.put("msg", "文件地址不存在!");
			} else {
				result.put("state", "sucess");
			}
		} catch (Exception e) {
			result = HttpProcessUtil.processException(e);
		}
		return result;
	}

	/**
	 * 协议信息查询(根据医疗机构名称及协议编号查询其医疗机构名称及协议编号列表)
	 */

	@RequestMapping(value = "agreementPage.do")
	@ResponseBody
	public Map<String, Object> query(HttpServletRequest request)
			throws Exception {
		Map<String, Object> result = null;
		UserDetails user = (UserDetails) request.getSession().getAttribute(
				"user");
		try {
			// 协议模块：统筹区域
			int page = Integer.parseInt(request.getParameter("page"));
			int pageSize = Integer.parseInt(request.getParameter("pageSize"));

			String healthcareProviderName = request
					.getParameter("healthcareProviderName");
			String healthcareProviderCode = request
					.getParameter("healthcareProviderCode");
			String agreementNo = request.getParameter("agreementNo");
			String agreementType = request.getParameter("agreementType");
			String dateAgreementEff = request.getParameter("dateAgreementEff");
			String dateAgreementEnd = request.getParameter("dateAgreementEnd");

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("healthcareProviderName", healthcareProviderName);
			map.put("healthcareProviderCode", healthcareProviderCode);
			map.put("agreementNo", agreementNo);
			map.put("agreementType", agreementType);
			map.put("dateAgreementEff", dateAgreementEff);
			map.put("dateAgreementEnd", dateAgreementEnd);
			map.put("userName", user.getUsername());

			result = this.agreementService.queryPage(page, pageSize, map);
		} catch (Exception e) {
			result = HttpProcessUtil.processException(e);
		}
		return result;
	}

	/**
	 * 协议信息查询(根据协议编号查询其协议详细信息)
	 */
	@RequestMapping(value = "agreementShow.do", method = RequestMethod.GET)
	public Map<String, Object> get(HttpServletRequest request) throws Exception {
		Map<String, Object> result = null;
		try {
			String str = request.getParameter("id");
			result = this.agreementService.get(str);
			result.put("path", filePath);
		} catch (Exception e) {
			result = HttpProcessUtil.processException(e);
		}
		return result;
	}

	/**
	 * 文件查询
	 */
	@RequestMapping(value = "getImage.do", method = RequestMethod.GET)
	public Map<String, Object> getimageList(HttpServletRequest request)
			throws Exception {
		Map<String, Object> result = null;
		try {
			String str = request.getParameter("id");
			result = this.agreementService.getImageList(str);
		} catch (Exception e) {
			result = HttpProcessUtil.processException(e);
		}
		return result;
	}

	/**
	 * 协议信息修改
	 */
	@RequestMapping(value = "update.do")
	public Map<String, Object> update(HttpServletRequest request)
			throws Exception {
		Map<String, Object> result = null;
		try {
			UserDetails user = (UserDetails) request.getSession().getAttribute(
					"user");
			String currentUser = user.getUsername();
			String str = HttpProcessUtil.readRequestBody(request);
			JSONObject transferJson = JSON.parseObject(str);
			// assembleTransferJsonUpdate(request, transferJson);

			result = this.agreementService.update(transferJson, currentUser);
		} catch (Exception e) {
			result = HttpProcessUtil.processException(e);
		}
		return result;
	}

	/**
	 * 协议信息修改状
	 */
	@RequestMapping(value = "delete.do")
	public Map<String, Object> delete(HttpServletRequest request)
			throws Exception {
		UserDetails user = (UserDetails) request.getSession().getAttribute(
				"user");
		Map<String, Object> result = null;
		try {
			String str = HttpProcessUtil.readRequestBody(request);
			JSONObject transferJson = JSON.parseObject(str);
			// assembleTransferJsonUpdate(request, transferJson);
			transferJson.put("updatedBy", user.getUsername());
			result = this.agreementService.delete(transferJson);
		} catch (Exception e) {
			result = HttpProcessUtil.processException(e);
		}
		return result;
	}

	/**
	 * 查询支付方式
	 */
	@RequestMapping("queryPayment.do")
	@ResponseBody
	public List<Map<String, String>> getModePay(HttpServletRequest request,
			HttpServletResponse response) {
		List<Map<String, String>> result = null;
		try {
			result = this.agreementService.getModePay();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}

	/**
	 * 文件信息修改状
	 */
	@RequestMapping(value = "deleteFile.do")
	public Map<String, Object> deleteFile(HttpServletRequest request)
			throws Exception {
		UserDetails user = (UserDetails) request.getSession().getAttribute(
				"user");
		Map<String, Object> result = null;
		try {
			String str = HttpProcessUtil.readRequestBody(request);
			JSONObject transferJson = JSON.parseObject(str);
			// assembleTransferJsonUpdate(request, transferJson);
			transferJson.put("updatedBy", user.getUsername());
			result = this.agreementService.deleteFile(transferJson);
		} catch (Exception e) {
			result = HttpProcessUtil.processException(e);
		}
		return result;
	}

	/**
	 * 下载文件
	 */
	@RequestMapping("downloadFile.do")
	@ResponseBody
	public void downloadFile(
			@RequestParam(value = "fileInfoId", defaultValue = "")
			String fileInfoId,
			@RequestParam(value = "fileName", defaultValue = "")
			String fileName, @RequestParam(value = "path", defaultValue = "")
			String path, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// String filePath = "D:\\mhis-fwa";
		StringBuffer urlPath = new StringBuffer().append(filePath).append(
				null == path ? "" : File.separator + path);
		DevLog.info("urlPath=" + urlPath);
		if (fileName != null && !"".equals(fileName)) {
			String suffix = fileName.substring(fileName.lastIndexOf('.'));
			BufferedOutputStream bos = null;
			String disposition = "attachment;filename="
					+ URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Content-disposition", disposition);
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(urlPath.append(File.separator)
						.append(fileInfoId).append(suffix).toString());
				bos = new BufferedOutputStream(response.getOutputStream());
				byte[] buffer = new byte[2048];
				while (fis.read(buffer) != -1) {
					bos.write(buffer);
					bos.flush();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				if (fis != null) {
					fis.close();
				}
				if (bos != null) {
					bos.close();
				}
			}

		}

	}

}
